SuperStrict
NoDebug
  
Rem  
bbdoc: MaxMod.AudioStream
End Rem
Module MaxMod.AudioStream
ModuleInfo "MaxMod: AudioStream 1.25"
ModuleInfo "Author: REDi - Cliff Harman"
ModuleInfo "License: MIT"

Import BRL.StandardIO
Import BRL.Timer
Import BRL.Audio
Import BRL.EndianStream
Import BRL.FreeAudioAudio
Import BRL.OpenALAudio
Import MaxMod.Music

?win32
Import BRL.DirectSoundAudio
Include "inc/directsoundaudiostream.bmx"
?
Include "inc/openalaudiostream.bmx"
Include "inc/freeaudioaudiostream.bmx"
Include "inc/wavstream.bmx"

Rem
bbdoc: Start a new audio stream.
returns: A TChannel Object
about:
<TABLE>
<TR><TH><B>Parameters:</B></TH><TH>Description:</TH></TR>
<TR><TD>URL</TD><TD>URL to the audio you want to stream<BR>also accepts TMusic objects</TD></TR>
<TR><TD>Loop</TD><TD>True to loop the stream forever<BR>False to play the stream only once (defaults to False)</TD></TR>
<TR><TD>Paused</TD><TD>True to create the stream in a paused state<BR>False to start playback on creation of the stream (defaults to False)</TD></TR>
</TABLE><P>
EndRem
Function CreateAudioStream:TChannel(URL:Object,Loop:Int=True,Paused:Int=False)
	Return TAudioStream.Create(URL,Loop,Paused)
EndFunction
 
Type TAudioStream Extends TChannel

	Global Timer:TTimer = CreateTimer(120)
	Global _onEnd:Int
	Field Music:TMusic
	Field writepos:Int
	Field paused:Int
	Field samplerate:Int = 44100
	Field KeepMusic:Int
	
	Function Create:TAudioStream(URL:Object,Loop:Int,Paused:Int)

		Local Keep:Int
		Local Music:TMusic
		If TMusic(URL)
			Music = TMusic(URL)
			Music.Seti(MM_LOOP,Loop)
			Keep=True
		Else
			Music = LoadMusic(URL)
			If Not music Return Null
			Music.Seti(MM_LOOP,Loop)
		EndIf
		Local Stream:TAudioStream
		' ugly way of finding out what audio driver to use.
		Local chan:TChannel = AllocChannel() ; If Not chan Return Null
		Select True
?win32 
			Case TDirectSoundChannel(chan)<>Null	; Stream = TDirectSoundAudioStream.Build(Music,Paused)
?
			Case TOpenALChannel(chan)<>Null			; Stream = TOpenALAudioStream.Build(Music,Paused)
			Case TFreeAudioChannel(chan)<>Null		; Stream = New TFreeAudioAudioStream
		EndSelect
		Stream.Music = Music
		Stream.KeepMusic = Keep
		Return Stream
	EndFunction

	Method New()
		AddHook EmitEventHook,eventhook,Self
	EndMethod

	Function eventhook:Object(id:Int,data:Object,context:Object)
		Local This:TAudioStream = TAudioStream(context) 
		If Not This Return data
		Local Event:TEvent = TEvent(data)
		If Event.Source=Timer And Event.ID=EVENT_TIMERTICK This.Update
		Return data
	End Function

	Method Update() Abstract

EndType
